﻿childMovies = [];
function AddCollection() {
    $.get("http://" + document.location.host + SiteRoot + "/Movie/AddCollection.ashx",
        function(data) {
            var divtoAdd = document.createElement('div');
            divtoAdd.id = 'AddCollectionInterface';
            divtoAdd.innerHTML = data;
            document.body.appendChild(divtoAdd);
            $("#AddCollectionInterface").css({ left: (window.innerWidth - 800) / 2 });
            $("#AddCollectionInterface").css({ top: 100 });
        });
}
function SaveNewCollection() {
    $.post("http://" + document.location.host + SiteRoot + "/Movie/SaveNewCollection.ashx", { name: $('#CollectionName').val() },
      function(data) {
          if (document.getElementById('UserCollections') == null) {
              var userCollections = document.createElement('select');
              userCollections.id = 'UserCollections';
              userCollections.name = 'userCollections.Id';
              userCollections.options[userCollections.options.length] = new Option($('#CollectionName').val(), data);
              var div = document.createElement('div');
              div.appendChild(userCollections);
              $('#CollectionFields').css({ display: '' });
              document.getElementById('CollectionsHolder').insertBefore(div, document.getElementById('CollectionFields'));
              //$('#CollectionsHolder').append(userCollections);
              $('#AddCollectionFirst').remove();
          }
          else {
              var userCollections = document.getElementById('UserCollections');
              userCollections.options[userCollections.options.length] = new Option($('#CollectionName').val(), data);
          }
          $.modal.impl.close();
      });   

}
function ClearThisCrumb(e, id) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    var newQueryString = "?";
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] && ft[0] != id) {
            newQueryString += "&" + ft[0] + "=" + ft[1];
        }
    }
    window.location = "http://" + window.location.host + "/" + window.location.pathname + newQueryString;
}
function LinkToIMDB(id) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/LinkToIMDB.ashx", { movieId: id },
        function(data) {
            $('#IMDBContent').html('');
            $('#IMDBContent').append(data);
        }
    );
}
function GetIMDBMovies(e, movie, movieId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/SearchIMDB.ashx", { searchVariable: movie, linkFunction: 'adf()', movieId: movieId },
        function(data) {
            $('#AppendInfo').html('');
            $('#AppendInfo').append(data);            
            $('#AppendInfo').modal();
        }
    );
}
function AddThisIMDB(iId, mId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/LinkMovieToIMDB.ashx", { movieId: mId, imdbId: iId },
        function(data) {
            var resp = data.split(":");
            if (resp[0] == '1') {
                RunIMDB(resp[1]);
            }
            else {
                alert('There was an error on the save');
            }
            $.modal.impl.close();
        }
    );
}
    var _lastMovieViewId;
function ViewIMDBTitleInfo(e, id) {
    setload();
    var row = document.getElementById('MovieDetailRow');
    if (row) {
        e.parentNode.parentNode.removeChild(row);
    }
    if (id != _lastMovieViewId) {
        var tr = document.createElement('tr');
        tr.id = "MovieDetailRow";
        var td = document.createElement('td');
        td.setAttribute('colspan', '6')
        td.id = "MovieDetailInfo";
        tr.appendChild(td);
        e.parentNode.parentNode.insertBefore(tr, e.parentNode.nextSibling);
        $.get("http://" + document.location.host + SiteRoot + "/" + "Services/GetIMDBInfo.ashx", { imdbId: id },
            function(data) {
                $('#MovieDetailInfo').html('');
                $('#MovieDetailInfo').append(data);
                setunload();
            }
        );
    }
    else {
        setunload();
    }
    _lastMovieViewId = id;
}
function GetIMDBFromUsers(id) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/GetIMDBInfo.ashx", { imdbId: id, asJson: '1' },
        function(data) {
            alert(data);
        }
    );
}
function RunIMDB(id) {
    setload();
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/GetIMDBInfo.ashx", { imdbId: id, asJson: '1' },
        function(data) {
            if (data == "Error") {
                LinkToIMDB(_movieID);
            }
            else {
                $('#IMDBContent').html('');
                $('#IMDBContent').append(data);
            }
            setunload();
        }
    );
}
function Search(v, m) {
    $('#Results').html('Loading...');
    setload();
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/ReturnResults.ashx", { searchVariable: v, movieId: m },
    function(data) {
        $('#Results').html('');
        $('#Results').append(data);
        try {
            $('#pane1').jScrollPane({ showArrows: true });
        }
        catch (ex) { /* alert(ex); */ }   
        setunload();
    }
);
}
function setload() {
    //_loading = 1;
    if (document.all) for (var i = 0; i < document.all.length; i++) document.all(i).style.cursor = 'wait';
    return 1;
}
function setunload() {
    //_loading = 0;
    if (document.all) for (var i = 0; i < document.all.length; i++) document.all(i).style.cursor = '';
    return 0;
}
//function RunImportofSpreadsheet() {
//    $.get("StartExport.ashx", { fileName: $('#FileNameHidden').val(),
//        sheet: $('#SheetNameHidden').val(), movieName: $('#MovieName').val(),
//        typeName: $('#MediaTypeName').val(), viewedName: $('#ViewedName').val(),
//        viewedType: $('#ViewedType').val(), collectionName: $('#CollectionName').val(),
//        pageName: $('#PageName').val()
//    },
//            function(data) {
//                $('#progress1').html('');
//                $('#progress1').append(data);
//            }
//        );
//        }
//function SelectSheet(s) {
//    $.get("RunExport.ashx", { fileName: _fileName, sheet: s.innerHTML },
//            function(data) {
//                $('#progress1').html('');
//                $('#progress1').append(data);
//            }
//        );
//        }
function addslashes(str) {
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\0/g,'\\0');
return str;
}
function stripslashes(str) {
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\\\/g,'\\');
str=str.replace(/\\0/g,'\0');
return str;
}
function GetFriendsMovieSearch(m) {
    //FriendsMovies
    setload();
    $.get("SearchFriendsMovies.ashx", { movie: m },
    function(data) {
        $('#FriendsMovies').html('');
        var dataSplit = data.split(':::');
        $('#FriendsMovies').append(dataSplit[1]);
        var count = dataSplit[0];
        if (dataSplit[0] == '') {
            count = 0;
        }      
        $('#SearchMainMenu').append(CreateMenuItem('FriendsMoviesTab', 'Friends', count));
        //        try {
        //            $('#pane1').jScrollPane({ showArrows: true });
        //        }
        //        catch (ex) { /* alert(ex); */ }   
        setunload();
    });
}
function GetMoviesSearch(m) {
    //FriendsMovies
    setload();
    $.get("AllMovies.ashx", { movie: m },
    function(data) {
        $('#AllMovies').html('');
        var dataSplit = data.split(':::');
        $('#AllMovies').append(dataSplit[1]);
        var count = dataSplit[0];
        if (dataSplit[0] == '') {
            count = 0;
        }
        $('#SearchMainMenu').append(CreateMenuItem('AllMoviesTab', 'All', count));  
        setunload();
    });
}
function GetAmazonMoviesSearch(m) {
    //FriendsMovies
    setload();
    $.get("SearchAmazonMovies.ashx", { movie: m },
    function(data) {
        $('#AmazonMovies').html('');
        var dataSplit = data.split(':::');
        $('#AmazonMovies').append(dataSplit[1]);
        var count = dataSplit[0];
        if (dataSplit[0] == '') {
            count = 0;
        }
        $('#SearchMainMenu').append(CreateMenuItem('AmazonMoviesTab', 'Amazon', count));
        setunload();
    });
}
function GetNetflixMoviesSearch(m) {
    //FriendsMovies
    setload();
    $.get("SearchNetflixMovies.ashx", { movie: m },
    function(data) {
        $('#NetflixMovies').html('');
        var dataSplit = data.split(':::');
        $('#NetflixMovies').append(dataSplit[1]);
        var count = dataSplit[0];
        if (dataSplit[0] == '') {
            count = 0;
        }
        $('#SearchMainMenu').append(CreateMenuItem('NetflixMoviesTab', 'Netflix', count));
        setunload();
    });
}
function SearchIMDBMovies(m) {
    //FriendsMovies
    setload();
    $.get("SearchIMDBMovies.ashx", { movie: m },
    function(data) {
    $('#IMDBMovies').html('');
        var dataSplit = data.split(':::');
        $('#IMDBMovies').append(dataSplit[1]);
        var count = dataSplit[0];
        if (dataSplit[0]=='')
        {
            count = 0;
        }
        $('#SearchMainMenu').append(CreateMenuItem('IMDBMoviesTab', 'IMDB', count));
        setunload();
    });
}
function CreateMenuItem(name, text, number) {
    var li = document.createElement('li');
    li.id = name;
    li.className = 'notactive';
    li.innerHTML = text + ' (' + number + ')';
    li.onclick = function() { ChangeSearchResult(this); };
    return li;
}
var selectedSearchTab = 'MyMovies';
function ChangeSearchResult(e) {
    $('#MovieHolder').html('');
    switch (e.id) {
        case 'FriendsMoviesTab':
            $('#MovieHolder').html($('#FriendsMovies').html());
            e.className = '';
            break;
        case 'IMDBMoviesTab':
            $('#MovieHolder').html($('#IMDBMovies').html());
            e.className = '';
            break;
        case 'MyMovies':
            $('#MovieHolder').html($('#UserMovies').html());
            e.className = '';
            break;
        case 'AllMoviesTab':
            $('#MovieHolder').html($('#AllMovies').html());
            e.className = '';
            break;
        case 'AmazonMoviesTab':
            $('#MovieHolder').html($('#AmazonMovies').html());
            e.className = '';
            break;
        case 'NetflixMoviesTab':
            $('#MovieHolder').html($('#NetflixMovies').html());
            e.className = '';
            break;
        default:
            break;
    }
    document.getElementById(selectedSearchTab).className = 'notactive';
    selectedSearchTab = e.id;
}
var selectedProfileTab = 'PersonalTab';
function ChangeProfileTab(e) {
    $('#ModifyProfile').html('');
    switch (e.id) {
        case 'ServicesTab':
            $('#ModifyProfile').html($('#Services').html());
            e.className = '';
            break;
        case 'PersonalTab':
            $('#ModifyProfile').html($('#Personal').html());
            e.className = '';
            break;
        default:
            break;
    }
    document.getElementById(selectedProfileTab).className = 'notactive';
    selectedProfileTab = e.id;
}
var _removeMovieId;
function RemoveMovieFromCollection(id) {
    _removeMovieId = id;
    confirm("Are you sure you want to remove this movie?", function() {
        setload();
        $.get("RemoveMovie.ashx", { userMovieId: _removeMovieId },
        function(data) {
            setunload();
            $('#removed').modal({
                close: false,
                position: ["20%", ],
                overlayId: 'confirmModalOverlay',
                containerId: 'confirmModalContainer',
                onShow: function(dialog) {
                    dialog.data.find('.message').append(data + ' was removed successfully!');
                    dialog.data.find('.yes').click(function() {
                        $.modal.close();
                        window.location = 'UserMovies.ashx';
                    });
                }
            });
        });
    });
}
function confirm(message, callback) {
    $('#confirm').modal({
        close: false,
        position: ["20%", ],
        overlayId: 'confirmModalOverlay',
        containerId: 'confirmModalContainer',
        onShow: function(dialog) {
            dialog.data.find('.message').append(message);
            dialog.data.find('.yes').click(function() {
                if ($.isFunction(callback)) {
                    callback.apply();
                }
                $.modal.close();
            });
        }
    });
}
function SetToViewed(e, id) {
    e.parentNode.innerHTML = 'Yes';
    //$(e).hide();
    setload();
    $.get("SetToView.ashx", { userMovieId: id },
        function(data) {
            if (data == 'Successful') {
                //var div = document.getElementById('ViewedDiv');
                //div.firstChild.innerHTML = 'True';
                //div.firstChild.href = SiteRoot + '/Movie/UserMovies.ashx?Viewed=true';
            }
            else {
                alert(data);
            }
            setunload();
        });
    }
function AddThisIMDBManually(id) {
    if ($('#IMDBMovieCode').val().length > 0) {
        AddThisIMDB($('#IMDBMovieCode').val(), id);
    }
    else {
        alert("Please enter an IMDB code to link");
    }
}
function GetSiteUpdate(id) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/SiteActivity.ashx", { Id: id },
        function(data) {
            $('#SiteUpdates').html('');
            $('#SiteUpdates').append(data);
            $('#SiteUpdates').modal();
        }
    );
    }
function AcceptFriend(id) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/AcceptFriend.ashx", { friendId: id },
        function(data) {
            $('#FriendIn' + data).hide();
        }
    );
}
function DeclineFriend(id) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/DeclineFriend.ashx", { friendId: id },
        function(data) {
            $('#FriendIn' + data).hide();
        }
    );
    }
function CheckForNotifications() {
}
function GetNetflixAuthPage() {
    $.get("NetflixAuthentication.ashx", { username: $('#netflixlogin').val(), password: $('#netflixpassword').val() },
        function(data) {
            $('#NetflixAuthentication').html(data);
        }
    );
    }
function CheckIfOwn(movieId, userMovieId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/CheckIfOwnMovie.ashx", { movieId: movieId, userMovieId: userMovieId, rand: (Math.random() * 10000) },
    function(data) {
        var split = data.split(':');
        if (split[0] != "0") {
            var stringToAppend = "<a href='Detail.ashx?userMovieId=" + split[0] + "'>In Your Collection";
            if (split.length > 2) {
                stringToAppend += "(" + split[2] + ")";
            }
            stringToAppend += "</a>";
            $('#BorrowCol' + split[1]).html(stringToAppend);
        }
        else {
            CheckIfAvailable(split[1]);
        }
    });
}
function AskToBorrow(userMovieId, userId) {
    confirm("Are you sure you request to borrow this movie?", function() {
        $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/RequestMovie.ashx", { userMovieId: userMovieId, friendId: userId },
        function(data) {
            var split = data.split(':');
            if (split[0] != "0") {
                $('#BorrowCol' + split[0]).html("Movie Requested to Borrow");
            }
        });
    });
}
function CheckIfAvailable(userMovieId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/CheckIfMovieAvailable.ashx", { userMovieId: userMovieId },
    function(data) {
        if (data != "0")
        {
            var split = data.split(':');
            $('#BorrowCol' + split[0]).html(split[1]);
        }
    });
}
function CheckIfAvailableMine(userMovieId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/CheckIfMovieAvailable.ashx", { userMovieId: userMovieId },
    function(data) {
        if (data != "0") {
            var split = data.split(':');
            var div = document.createElement('div');
            div.innerHTML = "Movie Unavailable";
            $('#MovieId' + split[0]).append(div);
        }
    });
}
function AllowToBorrow(requestId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/GetAllowRequestPage.ashx", { requestId: requestId, allow: true },
    function(data) {
    $('#MovieRequest').html(data);
        $('#MovieRequest').modal();
    });
}
function DeclineToBorrow(requestId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/GetAllowRequestPage.ashx", { requestId: requestId, allow: false },
    function(data) {
    $('#MovieRequest').html(data);
    $('#MovieRequest').modal();
    });
}
function ReturnMovie(requestId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/ReturnMovie.ashx", { requestId: requestId },
    function(data) {
    $('#RequestOut' + data).hide();
    CheckHideNotifications();
    });
    $.modal.impl.close();
}
function ConfirmAllowBorrow(requestId) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/AllowRequest.ashx", { requestId: requestId, allow: true, reason: escape($('#AdditionalInfo').val()) },
    function(data) {
    $('#RequestIn' + data).hide();
    CheckHideNotifications();
    });
    $.modal.impl.close();
}
function ConfirmDeclineBorrow(requestId, reason) {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Friends/AllowRequest.ashx", { requestId: requestId, allow: false, reason: escape($('#AdditionalInfo').val()) },
    function(data) {
        $('#RequestIn' + data).hide();
        CheckHideNotifications();
    });
    $.modal.impl.close();
}
function CheckHideNotifications() {
    if (document.getElementById('DetailNotificationsList').childNodes.length == 3) {
        document.getElementById('DetailNotificationsList').parentNode.style.display = 'none';
    }
}
//function SearchForRodunuMovie(e) {
//    $('#SearchForMovieDiv').modal();
//}
function SearchRodunuMovies() {
    var textToSearch = $('#MovieBox').val();    
    if (textToSearch.length > 0) {
        $.get("http://" + document.location.host + SiteRoot + "/" + "Services/SearchForMovie.ashx", { movieName: textToSearch, doByLetter: false, forPage: false },
        function(data) {
            $('#SearchResultsAdd').html(data);
            try {
                //$('#SearchResultsAdd').jScrollPane({ showArrows: true });
            }
            catch (ex) { /* alert(ex); */ }
            setunload();
        });
    }
    else {
        alert("Must enter a value to search.");
    }
    
    
}
function SearchForUserMovies() {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/SearchForUserMovie.ashx", { movieName: $('#SearchForMovieToLinkText').val(), doByLetter: false, forPage: false },
    function(data) {
        $('#SearchResultsAdd').html(data);
        try {
            $('#SearchResultsAdd').jScrollPane({ showArrows: true });
        }
        catch (ex) { /* alert(ex); */ }
        setunload();
    });
}
function AddChildrenToCollection(id){
    var children = "";
    for(var x=0; x<childMovies.length; x++) {
        children = children + childMovies[x] + ",";
    }
    window.location = "http://" + document.location.host + SiteRoot + "/" + "Movie/AddChildrenToCollection.ashx?userMovieId=" + id + "&childrenMovies=" + children;
}
function LinkMovie() {
    $('#SearchForMovieToLinkText').val($('#CurrentMovieName').html());
    $('#SearchForMovieToLinkDiv').modal();
}
function SearchRodunuMoviesToLink() {
    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/SearchForMovie.ashx", { movieName: $('#SearchForMovieToLinkText').val(), doByLetter: false, forPage: true },
        function(data) {
            if (data != "") {
                $('#SearchMovieToLinkResults').html(data);
                try {
                    $('#SearchMovieToLinkResults').jScrollPane({ showArrows: true });
                }
                catch (ex) { /* alert(ex); */ }
            }
        });
    }
function SelectRodunuMovieToLink(id) {
    window.location = "http://" + document.location.host + SiteRoot + "/" + "Movie/LinkMovieToMovie.ashx?userMovieId=" + $('#UserMovieId').val() + "&movieId=" + id; 
}
var _currentMovieSelection;
var _searchResultsData;
var _currentTitle = '';
function SelectRodunuMovie(id, e) {
    if (e && _currentMovieSelection) {
        if (e == _currentMovieSelection) {
            //set to false
            e.className = 'LinkMovieItem';
            if ($('#MovieBox').val().length == 0) {
                $('#MovieBox').val('');
            }
            $('#AddOriginalTitleText').html('');
            $('#AddOriginalTitle').hide();
            $('#OringinalMovieId').val('');
            _currentMovieSelection = null;
            return;
        }
    }
    if (_currentMovieSelection) {
        _currentMovieSelection.className = 'LinkMovieItem';
    }
    e.className = 'LinkMovieItemSelected';
    _currentMovieSelection = e;

    if ($('#MovieBox').val().length == 0) {
        $('#MovieBox').val(trim(e.parentNode.childNodes[3].innerHTML));
    }
    $('#AddOriginalTitleText').html(e.parentNode.childNodes[3].innerHTML);
    _currentTitle = trim(e.parentNode.childNodes[3].innerHTML);
    var span = document.createElement('span');
    span.onclick = MakeOwnMovie;
    span.innerHTML = '(Make this your title)';
    $('#AddOriginalTitleText').append(span);
    $('#AddOriginalTitle').show();
    $('#OringinalMovieId').val(id);

}
function MakeOwnMovie() {
    $('#MovieBox').val(_currentTitle);
}
function CancelLinkToMovie() {
    $('#SearchResultsAdd').html(_searchResultsData);
}
//    $.get("http://" + document.location.host + SiteRoot + "/" + "Services/GetMovieDetail.ashx", { id: id },
//        function(data) {
//            if (data != "") {
//                $('#SearchResultsAdd').html(data);
//            }
//            setunload();
//        });
//    }
// Removes leading whitespaces
function LTrim(value) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim(value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}
// Removes leading and ending whitespaces
function trim(value) {
    return LTrim(RTrim(value));
}
var RunningSearch = false;
var _SearchTimeout = 0;
var _lastSearchVariable = "";
function SearchForMoviesLoop() {
    //if (RunningSearch == false) {
    if ($('#MovieBox').val() != "") {
        //if ($('#MovieBox').val() != _lastSearchVariable) {
            RunningSearch = true;
            $.get("http://" + document.location.host + SiteRoot + "/" + "Services/SearchForMovie.ashx", { movieName: $('#MovieBox').val(), doByLetter: true, forPage: false },
                function(data) {
                    if (data != "0") {
                        _lastSearchVariable = $('#MovieBox').val();
                        if (data != _searchResultsData) {
                            _searchResultsData = data;
                            $('#SearchResultsAdd').html(data);
                            try {
                                $('#SearchResultsAdd').jScrollPane({ showArrows: true });
                            }
                            catch (ex) { /* alert(ex); */ } 
                        }
                        _SearchTimeout = setTimeout("SearchForMoviesLoop()", 1600);
                    }
                    RunningSearch = false;
                });
            //} else {
            //    _SearchTimeout = setTimeout("SearchForMoviesLoop()", 10);
            //}
    }
    else {
        _SearchTimeout = setTimeout("SearchForMoviesLoop()", 1000);
    }
    //}
}
var _movieName;
var _movieId;
var _userMovieName;
function AddToMyCollection(umname, mid, mname) {
    _movieName = mname;
    _movieId = mid;
    _userMovieName = umname;
    GetAddMovie();
    //$('#BorrowCol' + umid).html("Movie Added to Your Collection");
}
function GetAddMovie() {
    animatedcollapse.toggle('EnterMovie');
    GetAddMovieDetailInfo();
}
function GetAddMovieDetailInfo()
{
    $.get("http://" + document.location.host + SiteRoot + "/Services/AddMovie.ashx", {},
    function(data) {
        $('#EnterMovie').html(data);
        jQuery(function() {
            jQuery("#MovieBox").suggest("http://" + document.location.host + SiteRoot + "/Movie/UserMoviesJson.ashx", {
        });
        //        $('#MovieBox').keyup(function() {
        //            //Fill other box
        //            SearchForMoviesLoop();
        //        });
        $('#MovieBox').focus(function() {
            _lastSearchVariable = "";
            //_SearchTimeout = setTimeout("SearchForMoviesLoop()", 1000);
        });
        $('#MovieBox').blur(function() {
            clearTimeout(_SearchTimeout);
        });
        if (_movieId&&_movieName) {
            $('#OringinalMovieId').val(_movieId);
            $('#AddOriginalTitleText').html(_movieName);
            $('#AddOriginalTitle').show();
            _movieId = null;
            _movieName = null;
        }
        if (_userMovieName) {
            $('#MovieBox').val(_userMovieName);
            _userMovieName = null;
        }
        $('#MovieBox').focus();
    });
    if ($('#SavedMessage').text() != '') {
        setTimeout(ClearSaveMessage, 3000);
    }
    function ClearSaveMessage() {
        $('#SavedMessage').fadeOut("slow");
    }
    $('#AddCollectionExisting').click(function(e) {
        e.preventDefault();
        $('#basicModalContent').modal();
    });
    $('#AddCollectionFirst').click(function(e) {
        e.preventDefault();
        $('#basicModalContent').modal();
    });
});
}
function SaveNewMovieAjax() {
    $('#SaveNewMovieButton').attr('disabled', 'true');
    if ($("#MovieBox").val().length > 0) {
        var dataString = 'userMovies.Name=' + $("#MovieBox").val();
        dataString += '&movie.Id=' + $('#OringinalMovieId').val();
        if ($('#userMovies_Viewed').attr('checked') == undefined) {
            dataString += '&userMovies.Viewed=false';
        }
        else {
            dataString += '&userMovies.Viewed=' + $('#userMovies_Viewed').attr('checked');
        }
        dataString += '&userMovies.MovieTypes.Id=' + $('#userMovies_MovieTypes_Id').val();
        dataString += '&userCondition.Id=' + $('#userCondition_Id').val();
        dataString += '&userCollections.Id=' + $('#UserCollections').val();
        dataString += '&userMovies.Location=' + $('#userMovies_Location').val();

        $.ajax({
            type: "POST",
            url: "http://" + document.location.host + SiteRoot + "/Movie/AddSave.ashx",
            data: dataString,
            success: function(data) {
                if (data.length > 0) {
                    var response = data.split(":::");
                    if (response[0] != "0") {
                        $('#MovieSaveSuccessful').html('');
                        var div = document.createElement('div');
                        div.className = 'Title';
                        div.innerHTML = response[1] + ' was saved successfully!';
                        var ahref = document.createElement('a');
                        ahref.href = "http://" + document.location.host + SiteRoot + "/Movie/Detail.ashx?id=" + response[0];
                        ahref.innerHTML = 'Click here to view movie';
                        var addAnother = document.createElement('div');
                        addAnother.className = 'Clickable';
                        addAnother.innerHTML = 'Click here to add another';
                        addAnother.onclick = function() { BackFromSave(true); };
                        var done = document.createElement('div');
                        done.className = 'Clickable';
                        done.innerHTML = 'Click here to return';
                        done.onclick = function() { BackFromSave(false); };
                        var clickableHolder = document.createElement('div');
                        clickableHolder.className = 'ClickableHolder';
                        $('#MovieSaveSuccessful').append(div);
                        $('#MovieSaveSuccessful').append(ahref);
                        clickableHolder.appendChild(addAnother);
                        clickableHolder.appendChild(done);
                        $('#MovieSaveSuccessful').append(clickableHolder);
                        _isClosed = false;
                        $('#MovieSaveSuccessful').modal({ onClose: MovieSaveSuccessfulClose });
                    }
                    else {
                        alert('The save was unsuccessful! ' + response[1]);
                        animatedcollapse.toggle('EnterMovie');
                    }
                }
            }
        });
    }
    else {
        alert('You must enter a movie name!');
        $('#SaveNewMovieButton').attr('disabled', 'false');
    }
    return false;
}
function MovieSaveSuccessfulClose(dialog) {
    if (_isClosed == false) {
        animatedcollapse.toggle('EnterMovie');
    }
    $.modal.close();
}
var _isClosed = true;
function BackFromSave(t) {
    _isClosed = true;
    if (t) {
        //add another
        GetAddMovieDetailInfo();
    }
    else {
        //close
        animatedcollapse.toggle('EnterMovie');
    }
    $.modal.impl.close();
}
function MakeDefaultAmazon(movieId, amazonASIN) {
    $.get("MakeDefaultAmazon.ashx", { movieId: movieId, amazonASIN: amazonASIN },
        function(data) {
            if (data != "0") {
                window.location.reload(true);
            }
            else {
                alert('Error');
            }
        });
    }
    function MakeFavorite(umid) {
        var isFav;
        if ($('#DetailFavoriteLink').html() == 'Add to Favorites') {
            isFav = true;
        } else {
            isFav = false;
        }
        $.get("http://" + document.location.host + SiteRoot + "/Services/MakeMovieFavorite.ashx", { id: umid, favorite: isFav },
        function(data) {
            if (data != "0") {
                var res = data.split(":");
                if (res[1] == "True") {
                    $('#FavoriteIconMark').attr("style", "");
                    $('#DetailFavoriteLink').html("Remove from Favorites");
                } else {
                    $('#FavoriteIconMark').attr("style", "display:none");
                    $('#DetailFavoriteLink').html("Add to Favorites");
                }
            }
            else {
                alert('Error');
            }
        });
    }
    function SetFavoriteStatus(umid) {
        var isFav;
        if ($('#FavoriteIcon' + umid).attr('title') == 'Add To Favorites') {
            isFav = true;
        } else {
            isFav = false;
        }
        $.get("http://" + document.location.host + SiteRoot + "/Services/MakeMovieFavorite.ashx", { id: umid, favorite: isFav },
        function(data) {
            if (data != "0") {
                var res = data.split(":");
                if (res[1] == "True") {
                    $('#FavoriteIconMark' + res[0]).attr("style", "");
                    $('#FavoriteIcon' + res[0]).attr("src", "http://" + document.location.host + SiteRoot + "/Content/img/icons/remove_favorite18.png");
                    $('#FavoriteIcon' + res[0]).attr("title", "Remove From Favorites");
                } else {
                    $('#FavoriteIconMark' + res[0]).attr("style", "display:none");
                    $('#FavoriteIcon' + res[0]).attr("src", "http://" + document.location.host + SiteRoot + "/Content/img/icons/add_to_favorites18.png");
                    $('#FavoriteIcon' + res[0]).attr("title", "Add To Favorites");
                }
            }
            else {
                alert('Error');
            }
        });
    }
function AddToCollection(mid, did) {
    var found = false;
    for(var x=0; x < childMovies.length; x++) {
        if(childMovies[x] == mid) {
            found = true;
        }
    }
    
    if(found == false) {
        childMovies.push(mid);
    }

    var e = document.getElementById(did);
    var _removeIcon = "<img src='" + "http://" + document.location.host + SiteRoot + "/Content/img/delete-24x24.png' height='16px' />";
    e.innerHTML = "<span class='CollectionButton' onclick='RemoveFromCollection(&#39;" + mid + "&#39;, &#39;" + did + "&#39;);'>" + _removeIcon + "</span>";
    var result = document.getElementById("CollectionResult");
    result.innerHTML = "Items in collection: " + childMovies.length;
}
function RemoveFromCollection(mid, did) {
    var found = false;
    var newChildMovies = [];
    for(var x=0; x < childMovies.length; x++) {
        newChildMovies.push(childMovies[x]);
        if(childMovies[x] == mid) {
            newChildMovies.pop();
        }
    }
    
    childMovies = newChildMovies;
    var e = document.getElementById(did);    
    var _addIcon = "<img src='" + "http://" + document.location.host + SiteRoot + "/Content/img/add-24x24.png' height='16px' />";
    e.innerHTML = "<span class='CollectionButton' onclick='AddToCollection(&#39;" + mid + "&#39;, &#39;" + did + "&#39;);return false;'>" + _addIcon + "</span>";
    var result = document.getElementById("CollectionResult");
    result.innerHTML = "Items in collection: " + childMovies.length;
}

function RemoveMovieFromThisCollection(pid, mid) {
    $.get("../Services/RemoveUserMovieFromCollection.ashx", { parentId: pid, userMovieId: mid },
        function(data) {
            $('#ChildMovieCell').html(data);
        });
    }
function LinkNetflixToMovie(id, movieId) {
    $.get("http://" + document.location.host + SiteRoot + "/Services/LinkNetflixToMovie.ashx", { netflixId: id, movieId: movieId },
        function(data) {
            if (data == "1") {
                window.location.reload(true);
            } else {
                alert("Link for this movie already exists");
            }
        });
    }
function SearchAmazon(mid) {
        $('#AmazonSearchResultsHolder').show();
    $('#AmazonSearchResults').html('Loading...');
    setload();
    $.ajax({
        type: "GET",
        data: { title: $('#SearchAmazonMovieTitle').val(), id: mid },
        url: "../Search/SearchAmazon.ashx",
        dataType: "html",
        error: function() {
            $('#AmazonSearchResults').html('');
            $('#AmazonSearchResults').append(GetError('There was an error durning the search'));
        },
        success: function(data) {
            $('#AmazonSearchResults').html(data);
            setunload();
        }
    });
}
function SearchNetflix(mid) {
    $('#NetflixSearchResultsHolder').show();
    $('#NetflixSearchResults').html('Loading...');
    setload();
    $.ajax({
        type: "GET",
        data: { title: $('#SearchNetflixMovieTitle').val(), id: mid },
        url: "../Search/SearchNetflix.ashx",
        dataType: "html",
        error: function() {
            $('#NetflixSearchResults').html('');
            $('#NetflixSearchResults').append(GetError('There was an error durning the search'));
        },
        success: function(data) {
            $('#NetflixSearchResults').html(data);
            setunload();
        }
    });
}
function GetError(e) {
    var div = document.createElement('div');
    div.id = "ErrorMessage";
    var img = document.createElement("img");
    img.setAttribute('src', "http://" + document.location.host + SiteRoot + "/Content/img/ErrorCircle-32.png");
    img.style.height='26px';
    div.appendChild(img);
    var message = document.createElement('div');
    message.innerHTML = e;
    div.appendChild(message);
    return div;
}
function setload() {
    if (document.all) for (var i = 0; i < document.all.length; i++) document.all(i).style.cursor = 'wait';
    return 1;
}
function setunload() {
    if (document.all) for (var i = 0; i < document.all.length; i++) document.all(i).style.cursor = '';
    return 0;
}
function SwitchCollectionView(e) {
    if (e.innerHTML == '-') {
        $('#CollectionsList').hide();
        e.innerHTML = '+';
    }
    else {
        $('#CollectionsList').show();
        e.innerHTML = '-';
    }
}
function AddComment(userMovieId, userId, large) {
    if ($('#addcommentholder' + userMovieId).length == 0) {
        $('#Comments' + userMovieId).append(CreateComments(userMovieId, userId, large));
        $('#addcommenttextbox').focus();
        $('#addcommenttextbox').autogrow({
    });
}
}
function CreateComments(userMovieId, userId, large) {
    var addcomments = document.createElement('div');
    addcomments.id = 'addcommentholder' + userMovieId;
    
    var arrow = document.createElement('div');
    arrow.className = 'CommentArrow';
    var img = document.createElement('img');
    img.setAttribute('src', "http://" + document.location.host + SiteRoot + "/Content/img/CommentsArrow.jpg");
    arrow.appendChild(img);
    addcomments.appendChild(arrow);

    var div = document.createElement('div');
    if (large) {
        div.className = 'LargeCommentBox';
    }
    else {
        div.className = 'SmallCommentBox';
    }   
    div.innerHTML = '<span>Add Your Comments</span>';
    var textArea = document.createElement('textarea');
    textArea.id = 'addcommenttextbox' + userMovieId;
    textArea.className = 'expanding';
    div.appendChild(textArea);
    
    var button = document.createElement('input');
    button.type = 'button';
    button.value = 'Add Comments';
    button.className = 'Button';
    button.onclick = function() { SaveComment(userMovieId, userId, large); };
    div.appendChild(button);

    var cancel = document.createElement('input');
    cancel.type = 'button';
    cancel.value = 'Cancel';
    cancel.className = 'Button';
    cancel.style.marginLeft = '.5em';
    cancel.onclick = function() { CancelComment(userMovieId); };
    div.appendChild(cancel);

    addcomments.appendChild(div);
    return addcomments;
}
function CancelComment(userMovieId) {
    $('#addcommentholder' + userMovieId).remove();    
}
function SaveComment(userMovieId, userId, large) {
    $.ajax({
        type: "POST",
        data: { userMovieId: userMovieId, userId: userId, comment: escape($('#addcommenttextbox' + userMovieId).val()), isLarge: large },
        url: "../Comments/AddComment.ashx",
        dataType: "html",
        error: function() {
            alert('There was an error');
        },
        success: function(data) {
            var resp = data.split(":::");
            if (resp[0] > 0) {
                var div = document.createElement('div');
                div.innerHTML = resp[1];
                $('#addcommentholder' + resp[0]).replaceWith(div);
            }
            else {
                alert('There was an error');
            }
        }
    });
}
function GetAllComments(userMovieId) {
    $.ajax({
        type: "GET",
        data: { userMovieId: userMovieId },
        url: "../Comments/GetComments.ashx",
        dataType: "html",
        error: function() {
            alert('There was an error');
        },
        success: function(data) {
            var resp = data.split(":::");
            if (resp[0] > 0) {
                $('#Comments' + resp[0]).html(resp[1]);
            }
            else {
                alert('There was an error');
            }
        }
    });
}